import ISEMPTY from "lodash/isEmpty"
import REDUCE from "lodash/reduce";
import DROP from "lodash/drop";
import VALUES from "lodash/values";
import KEYS from "lodash/keys"
import DIFF  from 'lodash/difference'
import PARSEINT from 'lodash/parseInt'
import ISNAN  from  'lodash/isNaN'

const csvToKeyValue = function (Content,keys) {
    console.log(Content)
    let csvKeyValue = REDUCE(
        Content,
        function (result, item) {
            let obj = {}
            keys.forEach((key, index) => {
                if(ISNAN(PARSEINT(item.split(',')[index]))){
                    obj[key] = item.split(',')[index]
                }else{
                    obj[key] = PARSEINT(item.split(',')[index])
                }
                
            });
            result.push(obj)
            return result;
        },
        []
    );
    console.log(csvKeyValue)
    return csvKeyValue
}


export const readCSV = function (file,keyMap) {
    return new Promise((res, rej) => {
        var reader = new FileReader();
        if (typeof reader == "undefined") {
            rej("您的浏览器暂不支持该功能");
            return;
        }
        var fileName = file.name;
        var pointIndex = fileName.lastIndexOf(".");
        var fileSuffix = fileName.substr(pointIndex);
        if (fileSuffix == ".CSV" || fileSuffix == ".csv") {
            try {
                reader.readAsText(file, "utf-8");
                reader.onload = function (f) {
                    if (!ISEMPTY(this.result)) {
                        let csvContentTable = this.result.split("\r\n");
                        let Header = csvContentTable[0].split(",");
                        if(!ISEMPTY(DIFF(VALUES(keyMap),Header))){
                            rej("数据内容错误");
                        }else{
                            let Content = DROP(csvContentTable);
                            res(csvToKeyValue(Content,KEYS(keyMap)))
                        }
                    } else {
                        rej("选择的文件为空");
                    }
                };
            } catch (e) {
                rej("读取文件失败！");
                console.log(e);
            }
        } else {
            rej("您选择的文件不是CSV格式");
        }
    })
}